﻿/*
 *Author: Jeff Liu 
 *
 *Under MIT License
 *jebberwocky@gmail.com
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CtpGglPlaces.Interface;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace CtpGglPlaces.Impl
{
    public class JsonPlaceParser: IPlaceParser
    {
        public PlacesResult Parse(string json)
        {
            PlacesResult presult = new PlacesResult();
            JObject o = JObject.Parse(json);
            presult.Status = (String)o["status"];

            JArray presults = (JArray)o["results"];
            presult.Results = new List<PlaceObj>();
            for (int x = 0; x < presults.Count; x++)
            {
                PlaceObj pobj = new PlaceObj();
                JObject ojb = (JObject)presults[x];
                pobj.Name = (String)ojb["name"];
                JArray types = (JArray)ojb["types"];
                List<String> stypes = new List<String>();
                for (int i = 0; i < types.Count; i++)
                    stypes.Add((String)types[i]);
                pobj.Types = stypes;
                pobj.Vicinity = (String)ojb["vicinity"];
                JObject geo = (JObject)ojb["geometry"];
                JObject geo_location = (JObject)geo["location"];
                pobj.Geometry.Location = new GeoPointImpl(
                    DataUtil.StringToDouble(geo_location["lat"].ToString()),
                    DataUtil.StringToDouble(geo_location["lng"].ToString())
                    );
                pobj.Icon = (String)ojb["icon"];
                pobj.Reference = (String)ojb["reference"];
                pobj.Id = (String)ojb["id"];
                presult.Results.Add(pobj);
            }
            JArray htmls = (JArray)o["html_attributions"];
            presult.HtmlAttributions = new List<string>();
            for (int i = 0; i < htmls.Count; i++)
                presult.HtmlAttributions.Add((String)htmls[i]);
            return presult;
        }
    }
}
